<template>
  <head>
    <meta charset="UTF-8">
  </head>
  <div class="home-container">
    <el-row :span="24">
      <el-col :span="2"></el-col>
      <!-- 社团图片轮播-->
      <el-col :span="8">
        <div style="margin-top: 30px">
          <el-carousel :interval="5000" :height="carouselHeight">
            <el-carousel-item v-for="(path, index) in paths" :key="index">
              <img :src="path" alt="slide image" style="height: 300px;width: 400px;  object-fit: contain;" />
              <!-- 可以根据需要添加图片标题或其他内容 -->
            </el-carousel-item>
          </el-carousel>
        </div>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="13">
        <div class="clubname" style="display: flex; align-items: center">
          <div style="margin-left: 15px;text-align: left;">
            <h3>{{club.Cname}}</h3>
          </div>
          <el-button type="primary" style="margin-top:5px;margin-left:25px; height:25px; width: 80px;font-size: 14px;" @click="handleJoinClick">申请加入</el-button>
        </div>

        <!-- el-tag-->
        <div class="tag-group" style="margin-top: -6px">
          <!-- 社团等级：校级/所属学院 -->
          <el-tag type="primary" effect="plain" style="margin-right: 5px;"> {{ club.Unit }} </el-tag>
          <!-- 社团类别 -->
          <el-tag type="warning" effect="plain" style="margin-right: 5px;"> {{ getTypeText(club.Type) }} </el-tag>
          <!-- 社团地址 -->
          <el-tag type="success" effect="plain"> {{ getAddressText(club.Address)}} </el-tag>
        </div>
        <!-- 社团基本信息 -->
        <div class="clubinfo" style="margin-top: -6px">
          <p style="font-weight: 600;font-size: 17px;">社团宗旨：{{ club.Aim }}</p>
          <p style="font-weight: 600;font-size: 17px;margin-top: -12px">社团介绍：{{ club.Introduction }}</p>
          <p style="font-weight: 600;font-size: 17px;margin-top: -12px">创办时间：{{ club.Edate }}</p>
          <p style="font-weight: 600;font-size: 17px;margin-top: -12px">社团地址：{{ getAddressText(club.Address) }}</p>
          <p style="font-weight: 600;font-size: 17px;margin-top: -12px">联系电话：{{ club.Phone }}</p>
          <p style="font-weight: 600;font-size: 17px;margin-top: -12px">联系邮箱：{{ club.Mailbox }}</p>
          <p style="font-weight: 600;font-size: 17px;margin-top: -12px" v-if="club.Outstanding">社团风采：{{ club.Outstanding }}</p>
        </div>
      </el-col>
    </el-row>
  </div>

  <div v-if="dialogVisible" style="margin-top: 20px;text-align: left;margin-left: 180px;">
    <span style="font-size: 25px; ">社团活动</span>
  </div>
  <div class="c2">
    <div style="margin-top: 15px; width: 1100px;">
      <el-row>
        <el-col :span="24" v-for="(activity,index) in displayedActivities" :key="index">
          <el-card class="card" shadow="hover" :body-style="{ padding: '0px' }" style="height: 200px;width: 1000px;margin-bottom: 30px; margin: 12px; padding: 12px;">
            <el-row>
              <el-col :span="4"><img :src="getTypeLogo(activity.Type)" style="width: 50px; height:50px; margin-right: 32px; margin-top: 6px"></el-col>
              <el-col :span="15">
                <div style="margin-top: 7px;height: 50px; width: 660px;">
                  <p style="font-size: 24px; font-family: Arial;  float: left; font-weight: 600;  margin: 0 0 0px; text-align: left;
                              display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 1; overflow: hidden;text-overflow: ellipsis;">{{activity.ATitle}}</p>
                </div>
              </el-col>
              <el-col :span="3">
                <el-tag style="font-size: 18px; padding: 14px 28px;margin-top: 10px">{{getStateText(activity.State)}}</el-tag>
              </el-col>
              <el-col :span="1">
                <div @click="toggleCollect(activity.Aid,index)" style="margin-left: 20px;;">
                  <el-icon v-if="collected[index] === 1" :style="'color: #f9d423; font-size: 24px; position: absolute; top: 10px; right: 25px;'">
                    <StarFilled />
                  </el-icon>
                  <el-icon v-else :style="'color:#CCD8FFFF; font-size: 24px; position: absolute; top: 10px; right: 25px;'">
                    <Star />
                  </el-icon>
                </div>
              </el-col>
            </el-row>
            <div style="margin-top:-12px; margin-left:165px; height: 10px;width: 800px;text-align: left">
              <el-tag effect="dark" size='small' type="success" style="opacity: 0.7; font-size: 14px; padding:  8px 14px;">{{getCampusText(activity.Campus)}}</el-tag>
              <el-tag effect="dark" size='small' type="warning" style="opacity: 0.7; margin-left: 10px;font-size: 14px; padding: 8px 14px;">{{getTypeText(activity.Type)}}</el-tag>
              <el-tag v-if="getPermissionText(activity.Permission)" effect="dark" size="small" type="danger" style="opacity: 0.7; margin-left: 10px; font-size: 14px; padding: 8px 14px;">{{ getPermissionText(activity.Permission) }} </el-tag>
            </div>
            <div style="text-align: left; margin-left:165px; margin-top:25px; font-family: Arial; font-size: 18px;width: 700px; height: 100px;">
              <p style="font-size:16px; height:16px;"><strong><span style="font-size: 16px;">举办社团：</span></strong> {{clubNames[index]}}</p>
              <p style="font-size: 16px; height:16px;"><strong><span style="font-size: 16px;">举办地点：</span></strong> {{activity.Place}}</p>
              <p style="font-size: 16px; height:16px"><strong><span style="font-size: 16px;">报名时间：</span></strong> {{getFormatTime(activity.StartTime)}} - {{getFormatTime(activity.EndTime)}}</p>
              <p style="font-size: 16px; height:16px"><strong><span style="font-size: 16px;">举办时间：</span></strong> {{getFormatTime(activity.Stime)}} - {{getFormatTime(activity.Etime)}}</p>
            </div>
            <div>
              <el-button type="success" style="opacity: 0.95; margin-top: -50px; margin-left:720px; height:30px; width: 130px;font-size: 18px;" @click="showDialog(activity)">查看详情</el-button>
<!--              活动详情对话框-->
              <el-dialog v-model="dialogVisible" width=800px :modal="false" :before-close="handleClose">
                <div style="text-align: left; margin-left:60px; margin-top: -40px; font-family: Arial; width:630px;">
                  <p style="font-size: 26px;font-weight: 600;">{{ currentActivity.ATitle }} </p>
                  <span style="font-size:20px;font-weight: 550;">活动内容：</span>
                  <p style="font-size: 18px;" v-html="formattedContent"> </p>
                  <span style="font-size: 20px;font-weight: 550;">报名要求：</span>
                  <p style="font-size: 18px;" v-html="formattedRequirement"></p>
                </div>
                <div style="margin-top: 40px; display: flex;  justify-content: center;">
									<span>
										<el-button @click="dialogVisible = false">取消</el-button>
										<el-button type="primary" @click="joinActivity()">报名</el-button>
									</span>
                </div>
              </el-dialog>
              <div v-if="dialogVisible" class="overlay"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
<!--  入社申请对话框-->
  <el-dialog v-model="dialogVisible1" class="custom-dialog" @close="handleJoinClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名：" prop="name"> {{user.Uname}} </el-form-item>
          <el-form-item label="学号：" prop="user_id"> {{ user.UID }} </el-form-item>
          <el-form-item label="学院：" prop="college"> {{ user.Major }} </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请社团：" prop="club"> {{ club.Cname }} </el-form-item>
          <el-form-item label="社团类别：" prop="clubtype">{{ getTypeText(club.Type) }} </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="申请理由:" prop="joinReason">
        <el-input type="textarea" v-model="this.joinReason"></el-input>
      </el-form-item>
      <el-button type="primary" @click="handleJoinClub()">确定申请</el-button>
    </el-form>
  </el-dialog>
</template>


<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
export default {
  name: 'ClubDetail',

  data(){
    return{
      kind:1, //加入社团文件类型
      ifshow:'',//判断用户是否已经加入该社团，若已在社团，为0；若不在社团，为1
      club:[],//社团信息
      file:[],//社团相关附件
      user:[],//用户信息
      cid:'',
      type:'',
      paths:[],
      activeName: 'second',
      joinReason:'',
      dialogVisible1: false, //申请加入社团的可见判断
      clubname:'',
      level:'',
      aim:"社团致力于balabalabala",
      establishDate:"2018-3-20",
      ClubPhone:"17725727668",
      ClubMail:"2541627593@qq.com",
      introduction:"社团成立于...,日常开展...活动",
      spotpic:[],
      rules: {},

      //活动相关的data
      input: '',
      selection1: [],
      selection2: [],
      selection3: [],
      currentPage: 1,
      elementsPerPage:12,
      activities:[],
      clubNames:[],
      showactivities:[],
      collected:[],
      dialogVisible:false, //活动详情的可见判断
      currentActivity: {},
      response: {},
      //社团类别
      options: [
        {value: 1,label: '思想政治类'},
        {value: 2,label: '学术科技类'},
        {value: 3, label: '体育竞技类'},
        {value: 4, label: '志愿公益类'},
        {value: 5, label: '文化艺术类'}],
      //校区
      options1: [
        {value1: 1, label1: '南校园'},
        {value1: 2, label1: '北校园'},
        {value1: 3, label1: '珠海校区'},
        {value1: 4, label1: '深圳校区'},
        {value1: 5, label1: '东校园'},
        {value1: 6, label1: '五校园'}],
      //活动状态
      options2: [
        {value2: 1, label2: '待报名'},
        {value2: 2, label2: '报名中'},
        {value2: 3, label2: '待开展'},
        {value2: 4, label2: '开展中'},
        {value2: 5, label2: '已结束'}],

    }
  },
  computed: {
    getTypeText() {
      return (type) => {
        switch (type) {
          case 1:
            return '思想政治类';
          case 2:
            return '学术科技类';
          case 3:
            return '体育竞技类'
          case 4:
            return '志愿公益类'
          case 5:
            return '文化艺术类'
        }
      };
    },
    getAddressText(){
      return (address) => {
        switch (address) {
          case 1:
            return '南校园';
          case 2:
            return '北校园';
          case 3:
            return '珠海校区'
          case 4:
            return '深圳校区'
          case 5:
            return '东校园'
          case 6:
            return '五校园'
        }
      };
    },
    getStateText() {
      return (state) => {
        switch (state) {
          case 1:
            return '待报名';
          case 2:
            return '报名中';
          case 3:
            return '待开展';
          case 4:
            return '开展中';
          case 5:
            return '已结束';
          default:
            return '其它';
        }
      };
    },
    getCampusText() {
      return (Campus) => {
        switch (Campus) {
          case 1:
            return '南校区';
          case 2:
            return '北校区';
          case 3:
            return '珠海校区';
          case 4:
            return '深圳校区';
          case 5:
            return '东校区';
          case 6:
            return '五校园'
          default:
            return '';
        }
      };
    },
    getPermissionText() {
      return (permission) => {
        switch (permission) {
          case 1:
            return '仅本社团成员可报名';
          default:
            return '';
        }
      };
    },
    getTypeLogo() {
      return (type) => {
        switch (type) {
          case 1:
            return require('../assets/1.jpg');
          case 2:
            return require('../assets/2.jpg');
          case 3:
            return require('../assets/3.jpg');
          case 4:
            return require('../assets/4.jpg');
          case 5:
            return require('../assets/5.jpg');
          default:
            return '';
        }
      };
    },
    displayedActivities() {
      const startIndex = (this.currentPage - 1) * this.elementsPerPage;
      const endIndex = startIndex + this.elementsPerPage;
      return this.showactivities.slice(startIndex, endIndex);
    },
    filteredactivities() {
      const filteredactivities = this.activities.filter(activity => {
        const TypeMatch = this.selection1.length === 0 || this.selection1.includes(activity.Type);
        const campusMatch = this.selection2.length === 0 || this.selection2.includes(activity.Campus);
        const statusMatch =  this.selection3.length === 0 || this.selection3.includes(activity.State);
        const inputMatch = this.input ? activity.Aline.includes(this.input) : true;
        return inputMatch&&TypeMatch && campusMatch && statusMatch;
      });
      this.currentpage(filteredactivities.length)
      return filteredactivities;
    },
    formattedContent() {
      return this.currentActivity.Content.replace(/\r\n|\n/g, '<br>');
    },
    formattedRequirement() {
      return this.currentActivity.Requirement.replace(/\r\n|\n/g, '<br>');
    }
    },

  mounted() {
    const params = new URLSearchParams();

    params.append('uid', this.$store.state.userinfo.account);
    params.append('cid', this.$route.query.id);
    console.log(this.$route.query.id)

    axios.get('http://localhost:8080/api/club/ClubDetail', { params })
      .then(response => {
        this.club = response.data.data.club; //社团相关信息
        this.file = response.data.data.file; //社团相关附件
        this.user = response.data.data.userinfo;
        this.ifshow = response.data.data.ifShow;
        this.paths = response.data.data.Paths;
      })
      .catch(error => {
        console.error('Error fetching clubs:', error);
      });

      axios.get('http://localhost:8080/api/manager/GetClubDetailAct', { params })
        .then(response => {
          this.activities = response.data.data.activities;
          this.clubNames =response.data.data.clubNames;
          this.showactivities =response.data.data.activities;
          this.collected = response.data.data.collected;
        })
        .catch(error => {
          console.error('Error fetching activities:', error);
        });




  },
  methods:{
    download(url) {
      const xhr = new XMLHttpRequest(); // 注意：这里是 XMLHttpRequest，而不是 newXMLHttpRequest()
      xhr.open('GET', url);
      xhr.responseType = 'blob';
      xhr.send();

      xhr.onload = function() {
        const fileBlob = xhr.response;
        const fileUrl = URL.createObjectURL(fileBlob);
        console.log(fileUrl);

        const elementA = document.createElement('a');
        elementA.setAttribute('href', fileUrl);


        elementA.innerHTML = '下载';
        elementA.setAttribute('download', '《加入社团申请表》.docx');
        elementA.style.display = 'none'; // 隐藏下载链接

        document.body.appendChild(elementA); // 将链接添加到页面中
        elementA.click(); // 模拟点击下载

        // 清理创建的 URL 对象
        URL.revokeObjectURL(fileUrl);
      };
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleSuccess(response) {
      // 文件上传成功的回调函数
      console.log('上传成功', response);
    },
    beforeUpload(file) {
      // 在上传之前的钩子函数，可以在这里做一些校验或者其他处理
      console.log('准备上传', file);
      return true; // 返回 true 表示继续上传，返回 false 将取消上传
    },
    //是展示活动详情的函数
    showDialog(activity) {
      this.dialogVisible = true;
      this.currentActivity = activity;
    },
    //申请报名社团函数
    JoinClub(){
      const JoinData = new FormData();
      var getTime = new Date().getTime(); //获取到当前时间戳
      var time = new Date(getTime); //创建一个日期对象
      var currenttime=this.getFormatTime(time)

      JoinData.append('cid',this.club.Cid)
      JoinData.append('uid',this.$store.state.userinfo.account)
      JoinData.append("currentTime",currenttime)
      JoinData.append('file',this.joinFile)
      JoinData.append('reason',this.joinReason)


      //向后端post
      axios.post('api/club/submitForm', JoinData)
      .then(response => {
        var apply_state=response.data.data.apply_state
        //0已提交，1已经通过，2驳回，3取消，4提交申请成功
        if(apply_state==0){
          ElMessage.warning("您已经申请过该社团,请勿重复申请！");
        }else {
          ElMessage.success("申请加入社团成功！");
        }
        console.log('Form submitted successfully:', response);
      })
      .catch(error => {
        ElMessage.error("申请加入社团失败！");
        console.error('Error submitting form:', error);
      });
    },
    handleJoinClub(){
      this.JoinClub();
      this.dialogVisible1=false;
      this.joinReason='';
      },
    handleJoinClick() {
      if (this.ifshow === 1) {
        this.dialogVisible1 = true;
      } else if (this.ifshow === 0) {
        ElMessage.warning("您已是该社团成员，请勿重复申请！");
      }
    },
    handleJoinClose(){
      this.joinReason='';
    },
    joinActivity(){
      const formData = new FormData()
      formData.append('uid', this.$store.state.userinfo.account)
      formData.append('aid', this.currentActivity.Aid)
      var getTime = new Date().getTime(); //获取到当前时间戳
      var time = new Date(getTime); //创建一个日期对象
      var currenttime=this.getFormatTime(time)
      formData.append('time',currenttime)

      axios.post('/api/joinActivity', formData)
          .then(response => {
            this.response = response.data.data.permission;

            switch (this.response) {
              case 0:
                ElMessage.success('报名成功');
                break;
              case 1:
                ElMessage.warning('您已报名参加，请耐心等待结果');
                break;
              case 2:
                ElMessage.warning('您已报名成功，无需再报名');
                break;
              case 3:
                ElMessage.warning('该活动仅限社团成员参加');
                break;
              default:
                ElMessage.error('未知响应');
            }
            this.dialogVisible=false;
          })
          .catch(error => {
            console.error('Error joining activity:', error);
          });
    },
    toggleCollect(aid,index) {
      const collectedStatus = this.collected[index];
      this.sendCollectStatus(aid,collectedStatus,index);
    },
    sendCollectStatus(aid,collectedStatus,index) {
      const formData = new FormData()
      formData.append('uid', this.$store.state.userinfo.account)
      formData.append('aid',aid)
      formData.append('collected',collectedStatus)
      // 使用axios或其他HTTP客户端库发送POST请求
      axios.post('/api/activity/CollectActivity', formData)
          .then(response => {
            console.log(response);
            this.collected[index] = this.collected[index] === 1 ? 0 : 1;// 切换收藏状态
          })
          .catch(error => {
            ElMessage.error('收藏操作失败！')
            console.error(error);
          });
    },
    getFormatTime(time) {
      let date = new Date(time);
      let year = date.getFullYear();
      let month = (date.getMonth() + 1).toString().padStart(2, '0');
      let day = date.getDate().toString().padStart(2, '0');
      let hours = date.getHours().toString().padStart(2, '0');
      let minutes = date.getMinutes().toString().padStart(2, '0');
      let seconds = date.getSeconds().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
  props: {
    msg: String
  }
};
//     document.addEventListener('DOMContentLoaded', function() {
//     // 替换这里的URL为你想要下载的文件的实际URL
//     var fileUrl = 'https://docs.google.com/document/d/1bh9YJpN-GACA4cWMQGt3WXyuKNJeQ-3B/edit?usp=drive_link&ouid=100739240280194732178&rtpof=true&sd=true';

//     // 获取下载链接的元素
//     var downloadLink = document.getElementById('downloadLink');

//     // 设置下载链接的href属性为文件的URL
//     downloadLink.href = fileUrl;

//     // 设置下载链接的下载属性，使浏览器能够直接下载文件
//     downloadLink.setAttribute('download', '');

//     // 添加点击事件监听器（可选）
//     // downloadLink.addEventListener('click', function(event) {
//     //     // 可以在这里添加点击链接时的自定义逻辑
//     //     // 例如，显示一个提示或者进行其他操作
//     // });
// });


</script>

<style>
.custom-dialog {
  font-family: Arial, sans-serif; /* 设置字体 */
}

.el-dialog__body {
  padding: 20px; /* 添加内边距 */
}

.demo-ruleForm .el-form-item__label {
  width: 100px; /* 设置标签宽度 */
}
.tag-group {
  display: flex;
  justify-content: flex-start;
}

.clubinfo{
  font-family: 楷体;
  text-align: left; /* 文本左对齐 */
  /* display: flex; */
  /* justify-content: flex-start; */
}

/* 按钮样式 */
.click_btn{
  /* display: flex; */
  background-color: #2E8B57; /* 墨绿色 */
  text-align: left;
  /* height: 20px;
  width: 35px; */
    color: #fff; /* 文字颜色为白色 */
    border: none; /* 移除边框 */
    width: 55px;
    height: 16px;
    border-radius: 5px; /* 设置圆角 */
    padding: 10px 20px; /* 设置内边距 */
    font-size: 13px; /* 字体大小 */
    cursor: pointer; /* 鼠标悬停时显示手型 */
    transition: background-color 0.3s ease; /* 添加过渡效果 */

}

/* 按钮悬停样式 */
.click_btn:hover{
  background-color: #3CB371;
}

/* 下载链接的样式 */
.download-link {
  color: rgba(0, 179, 255, 0.879); /* 设置链接文字颜色为蓝色 */
  text-decoration: underline; /* 添加下划线效果 */
}

.attachment-list {
  list-style: none;
  padding: 0;
}
.attachment-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
}
.attachment-item:last-child {
  border-bottom: none;
}
.attachment-icon {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}
.attachment-name {
  flex: 1;
}

.c2{
  display: flex;
  justify-content: center;
  align-items: center;
}


.clubinfo {
  width:630px;
}

.clubinfo p {
  max-width: 100%; /* 防止单个段落内容过宽 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 文本溢出时显示省略号 */
}
</style>

